#!/usr/bin/env python
# coding: utf-8
# @Time   : 2022/11/25 11:24
# @Author : 梁灿

import pytest,allure,base64
from py.xml import html
from selenium import webdriver
from common.readconfig import ini
from config.config import cm
from page_web.PC.login import LoginPage
from datetime import datetime
from tools.times import timestamp
from tools.send_mail import send_report

# 全局设置driver方法1
driver = None


@pytest.fixture(scope='session')  # 以实现多个.py跨文件使用一个session来完成多个用例
def drivers():
    global driver
    '''定义全局driver参数'''
    if driver is None:
        driver = webdriver.Chrome()
        driver.maximize_window()

    driver.get(ini.url)
    driver.implicitly_wait(10)
    print("正在启动浏览器:Chrome")

    yield driver
    driver.close()
    print("正在退出浏览器:Chrome")
    return driver


@pytest.fixture(scope='session')  # 以实现多个.py跨文件使用一个session来完成多个用例
def drivers1():
    global driver
    '''定义全局driver参数'''
    if driver is None:
        driver = webdriver.Chrome()
        driver.maximize_window()

    driver.get(ini.url1)
    driver.implicitly_wait(10)
    print("正在启动浏览器:Chrome")

    yield driver
    driver.close()
    print("正在退出浏览器:Chrome")
    return driver


@pytest.fixture(scope='session')  # 以实现多个.py跨文件使用一个session来完成多个用例
def login(drivers):
    login = LoginPage(drivers)
    login.input_username('admin')
    login.input_password('123456')
    login.in_login()


@pytest.fixture(scope='session')  # 以实现多个.py跨文件使用一个session来完成多个用例
def login1(drivers1):
    login = LoginPage(drivers1)
    login.input_username('18875272518')
    login.input_password('123456')
    login.in_login()


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    当测试失败的时候，自动截图，展示到html报告中
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)
    extra = getattr(report, 'extra', [])

    if report.when == 'call' or report.when == "setup":
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            screen_img = _capture_screenshot()
            if file_name:
                html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def pytest_html_report_title(report):
    report.title = "球星卡项目web测试报告"


def pytest_configure(config):
    # config._metadata.clear()  # 清空原先Environment中的内容
    config._metadata['测试项目'] = "球星卡项目"
    config._metadata['测试地址'] = "http: //qxk.admin.sauou.com/,http: //qxk.shop.sauou.com/"


def pytest_html_results_summary(prefix, summary, postfix):
    # prefix.clear() # 清空summary中的内容
    prefix.extend([html.p("所属部门: 重庆派维特公司测试部")])
    prefix.extend([html.p("测试执行人: 梁灿")])


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """收集测试结果"""
    result = {
        "total": terminalreporter._numcollected,
        'passed': len(terminalreporter.stats.get('passed', [])),
        'failed': len(terminalreporter.stats.get('failed', [])),
        'error': len(terminalreporter.stats.get('error', [])),
        'skipped': len(terminalreporter.stats.get('skipped', [])),
        # terminalreporter._sessionstarttime 会话开始时间
        'total times': timestamp() - terminalreporter._sessionstarttime
    }
    print(result)
    if result['failed'] or result['error']:
        send_report()

def pytest_html_results_table_header(cells):
    cells.insert(1, html.th('测试标题'))
    cells.insert(2, html.th('测试描述'))
    cells.pop()  # 将原有的test删除

def pytest_html_results_table_row(report, cells):
    cells.insert(2, html.td(report.description))
    cells.insert(3, html.td(datetime.utcnow(), class_='col-time'))
    # cells.insert(1,html.td(report.nodeid))
    cells.pop()

# def pytest_html_results_table_row(report, cells):
#     cells.insert(1, html.td(report.description))
#     cells.insert(2, html.td(report.nodeid))
#     cells.pop(2)


def pytest_html_results_table_html(report, data):
    if report.passed:
        del data[:]
        data.append(html.div('通过的用例未捕捉日志输出', class_ ='empty.log'))


def _capture_screenshot():
    """截图保存为base64"""
    now_time, screen_file = cm.screen_path
    driver.save_screenshot(screen_file)
    allure.attach.file(screen_file,
                       "失败截图{}".format(now_time),
                       allure.attachment_type.PNG)
    with open(screen_file, 'rb') as f:
        imagebase64 = base64.b64encode(f.read())
    return imagebase64.decode()

